package controller.welcome;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.touch.sms.demo.SendMessageThread;
import controller.common.BaseController;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import properties.SystemProperty;
import response.CommonResult;
import services.expertInfo.ExpertBaseServices;
import services.upms.AccountServices;
import services.upms.PermissionServices;
import util.cryptogram.MD5Util;
import validator.*;
import wt.entity.expertInfo.ExpertBase;
import wt.entity.upms.Account;
import wt.entity.upms.AccountExample;
import wt.entity.upms.Permission;
import wt.staticData.ShortData;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 功能:
 * 作者: 洪世成
 * 日期: 2017/9/9
 * 版权所有: admin
 */
@Controller
@RequestMapping("welcome/signUp")
public class SignUpController extends BaseController {
    @Autowired
    PermissionServices permissionServices;
    @Autowired
    ExpertBaseServices expertBaseServices;
    @Autowired
    AccountServices accountServices;


    @RequestMapping(value = "validatorAccountPage")
    public String activeAccountPage(Integer flag, Map map) {
        map.put("flag", flag);
        return "welcome/signUp/validatorAccount";
    }

    @RequestMapping(value = "setPasswordPage")
    public String setPasswordPage() {
        return "welcome/signUp/setPassWord";
    }


    @ResponseBody
    @RequestMapping("getPhoneCode")
    public CommonResult getPhoneCode(Integer flag, String name, String idCard, String phone, HttpServletRequest request) throws Exception {

        CommonResult commonResult = new CommonResult();
        ComplexResult result = FluentValidator.checkAll().failOver()
                .on(flag, new SizeFluentValidator(1, 2, "标识"))
                .on(name, new NotBlankFluentValidator("姓名"))
                .on(idCard, new IdCardFluentValidator("身份证号"))
                .on(phone, new MobileFluentValidator("手机号码"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            commonResult.addMessage(result);
            return commonResult.setError();
        }
        idCard = idCard.toUpperCase();

        ExpertBase expertBase = expertBaseServices.selectByIdCard(idCard);
        if (expertBase == null) {
            commonResult.setMessage("您的基本信息尚未录入系统，请联系管理员。");
            return commonResult;
        }

        if (!name.equals(expertBase.getName())) {
            commonResult.setMessage("您的姓名和身份证不匹配");
            return commonResult;
        }

        if (!phone.equals(expertBase.getPhone())) {
            commonResult.setMessage("您的手机号码和身份证不匹配");
            return commonResult;
        }

        AccountExample accountExample = new AccountExample();
        accountExample.createCriteria().andExpertIdEqualTo(expertBase.getId());
        List<Account> accountList = accountServices.selectByExample(accountExample);


        if (flag == 1) {
            if (!accountList.isEmpty()) {
                commonResult.setMessage("您的账号已经激活！");
                return commonResult;
            }
        } else {
            if (accountList.isEmpty()) {
                commonResult.setMessage("您的账户还未激活,请激活账户！");
                return commonResult;
            }
        }

        HttpSession session = request.getSession();
        Date oldCodeTime = (Date) session.getAttribute("codeTime");
        if (oldCodeTime != null) {
            if (new Date().getTime() - oldCodeTime.getTime() < 50 * 1000) {
                commonResult.setMessage("操作过于频繁");
                return commonResult;
            }
        }

        Random r = new Random();
        int codeNum = r.nextInt(899999) + 100000;
        String message = "验证码为：" + codeNum + "，请勿将验证码透露给他人。上海市质监局";

        try {
            SendMessageThread sendMessageThread = new SendMessageThread(phone, message);
            sendMessageThread.start();
        } catch (Exception e) {
            log.warn("【Manual】=>{}", e.getMessage());
            commonResult.setMessage("短信发送异常");
            return commonResult;
        }


        session.setAttribute("codeTime", new Date());
        session.setAttribute(idCard, flag + name + idCard + phone + codeNum);

        log.info("codeNum:{}", codeNum);
        commonResult.setData(codeNum);
        return commonResult.setSuccess();

    }


    /**
     * 验证基本信息和短信验证码 首次激活账户
     *
     * @param name
     * @param idCard
     * @param phone
     * @param code
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "validatorInfo")
    public CommonResult activeAccountInit(Integer flag, String name, String idCard, String phone, Integer code, HttpServletRequest request) throws Exception {

        CommonResult commonResult = new CommonResult();
        ComplexResult result = FluentValidator.checkAll().failOver()
                .on(flag, new SizeFluentValidator(1, 2, "标识"))
                .on(name, new NotBlankFluentValidator("姓名"))
                .on(idCard, new IdCardFluentValidator("身份证号"))
                .on(phone, new MobileFluentValidator("手机号码"))
                .on(code, new NotNullFluentValidator("验证码"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            commonResult.addMessage(result);
            return commonResult.setError();
        }
        idCard = idCard.toUpperCase();

        HttpSession session = request.getSession();
        Date codeTime = (Date) session.getAttribute("codeTime");
        String message = (String) session.getAttribute(idCard);

        if (codeTime == null || (new Date().getTime() - codeTime.getTime() > 3600 * 1000)) {
            commonResult.setMessage("请重新获取验证码");
            return commonResult;
        }

        if (StringUtils.isBlank(message) || !message.equals(flag + name + idCard + phone + code)) {
            commonResult.setMessage("请重新获取验证码");
            return commonResult;
        }

        ExpertBase expertBase = expertBaseServices.selectByIdCard(idCard);
        request.getSession().setAttribute("_userLoginName", "system");

        if (flag == 1) {
            Account account = new Account();
            account.setLoginName(idCard);
            account.setPassword(idCard);
            account.setLive(ShortData.s1);
            account.setExpertId(expertBase.getId());
            account.setCreateTime(new Date());
            List<Permission> permissionList = permissionServices.selectByRoleId(SystemProperty.getExpertRoleId());
            List<String> permissionIdList = new ArrayList<String>();
            for (Permission permission : permissionList) {
                permissionIdList.add(permission.getId());
            }
            account.setRoleId(SystemProperty.getExpertRoleId());
            accountServices.insertSelective(account, permissionIdList);
        }
        session.setAttribute("expertValidator", expertBase);
        return commonResult.setSuccess();
    }


    @ResponseBody
    @RequestMapping(value = "setPassword")
    public CommonResult setPassword(String password, HttpServletRequest request) throws Exception {
        CommonResult commonResult = new CommonResult();
        if (StringUtils.isBlank(password)) {
            commonResult.setMessage("密码能为空");
            return commonResult;
        }


        HttpSession session = request.getSession();
        ExpertBase expertBase = (ExpertBase) session.getAttribute("expertValidator");
        if (expertBase==null) {
            commonResult.setMessage("请刷新页面重新操作");
            return commonResult;
        }

        AccountExample accountExample = new AccountExample();
        accountExample.createCriteria().andExpertIdEqualTo(expertBase.getId());
        Account account = accountServices.selectByExample(accountExample).get(0);
        account.setPassword(MD5Util.md5Hex(password));
        commonResult.setStatus(accountServices.updateByPrimaryKeySelective(account));



        //在老专系统填加专家
        PostMethod postMethod = null;
        try {
            postMethod = new PostMethod(SystemProperty.getCreateExpertAccountUrl());
            postMethod.addParameter("idCard",expertBase.getIdCard());
            postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            new HttpClient().executeMethod(postMethod); // 执行postMethod,调用http接口
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
        }



        return commonResult;
    }


}